/**
 * Created by hp on 2018/11/15.
 */
$(function () {
    $("#province").cityPicker({
        title: "选择城市",
        toolbarCloseText: "完成",
        onChange: function (picker, values, displayValues) {
            $("#city").val(values[1]);
            $("#district").val(values[2]);
            $(".project").val("");
            $("#projectName").val("");
            $("#building").val("");
            $("#unit").val("");
            $("#roomNumber").val("");
            $("#area").val("");

            $(".projectNameList").hide();
            $(".buildingList").hide();
            $(".unitList").hide();
            $(".houseList").hide();
        }
    });

    function getProjectName() {
        $("#communityId").val("");
        $("#building").val("");
        $("#unit").val("");
        $("#floor").val("");
        $("#roomNumber").val("");
        $("#area").val("");

        $(".buildingList").hide();
        $(".unitList").hide();
        $(".floorList").hide();
        $(".houseList").hide();
        $.ajax({
            type: "POST",
            url: "/wechatOpportunity/wxGetCommunityByDistrict",
            data: {
                projectName: $("#projectName").val(),
                city: $("#city").val(),
                district: $("#district").val(),
            },

            success: function (data) {
                if (data.status == "success") {
                    $(".projectNameList").html("");
                    var projectNameList = data.projectNameList;
                    $(".projectNameList").show();
                    if (projectNameList.length > 0) {
                        $(".projectNameListDiv .alertInfo").hide();
                        var content = '';

                        for (var i = 0; i < projectNameList.length; i++) {
                            content += '<div class="weui-media_box weui-media_text item">';
                            content += '<h4 class="weui-media_title">' + projectNameList[i].communityName + '</h4>';
                            content += '<p class="weui-media_desc">' + projectNameList[i].address + '</p>';
                            content += '<span class="hide">' + projectNameList[i].communityId + '</span>';
                            content += '</div>'

                        }
                        $(".projectNameList").append(content);
                    }  else {
                        $(".projectNameListDiv .alertInfo").text("未找到对应的小区，请手动输入！").show();
                    }

                }

                else {
                    console.log("获取小区接口返回异常：" + data.errorMsg);
                }
            },
            error: function () {
                console.log("获取小区接口请求失败");
            }
        });
    }

    function getBuilding() {
        $("#buildingId").val("");
        $("#unit").val("");
        $("#floor").val("");
        $("#roomNumber").val("");
        $("#area").val("");
        $(".unitList").hide();
        $(".floorList").hide();
        $(".houseList").hide();
        $.ajax({
            type: "POST",
            url: "/wechatOpportunity/wxGetBuildingByCommunity",
            data: {
                cityId: $("#city").val(),
                communityId: $("#communityId").val(),
                building: $("#building").val(),
            },

            success: function (data) {
                if (data.status == "success") {
                    var dataList = data.buildingList;
                    if (dataList.length > 0) {

                        $('.buildingList').html("");
                        for (var i = 0; i < dataList.length; i++) {
                            var content = '<p class="item" dataBuildingId="' + dataList[i].buildingId + '">' + dataList[i].buildingName + '</p>';
                            $(".buildingList").append(content);
                        }
                        $(".buildingList").show();
                    } else {
                        $(".projectNameListDiv .alertInfo").text("未找到对应的楼栋，请手动输入！").show();
                    }

                }
                else {
                    console.log("获取楼栋接口返回异常：" + data.errorMsg);
                }
            },
            error: function () {
                console.log("获取楼栋接口请求失败");
            }
        });
    }

    function getUnit() {
        $("#unitId").val("");
        $("#roomNumber").val("");
        $("#floor").val("");
        $("#area").val("");

        $(".floorList").hide();
        $(".houseList").hide();
        $.ajax({
            type: "POST",
            url: "/wechatOpportunity/wxGetUnitByBuilding",
            data: {
                cityId: $("#city").val(),
                communityId: $("#communityId").val(),
                buildingId: $("#buildingId").val(),
                unit: $("#unit").val(),
            },

            success: function (data) {
                if (data.status == "success") {
                    var dataList = data.unitList;
                    if (dataList.length > 0) {

                        $('.unitList').html("");
                        for (var i = 0; i < dataList.length; i++) {
                            var content = '<p class="item" dataUnitId="' + dataList[i].unitId + '">' + dataList[i].unitName + '</p>';
                            $(".unitList").append(content);
                        }
                        $(".unitList").show();
                    }else {
                        $(".projectNameListDiv .alertInfo").text("未找到对应的单元，请手动输入！").show();
                    }

                }
                else {
                    console.log("获取单元接口返回异常：" + data.errorMsg);
                }
            },
            error: function () {
                console.log("获取单元接口请求失败");
            }
        });
    }


    function getFloorAndHouse() {
        $("#area").val("");
        $(".houseList").hide();
        $.ajax({
            type: "POST",
            url: "/wechatOpportunity/wxGetHouseByUnit",
            data: {
                cityId: $("#city").val(),
                buildingId: $("#buildingId").val(),
                unitId: $("#unitId").val(),
                floor: $("#floor").val(),
            },

            success: function (data) {
                if (data.status == "success") {
                    var dataList = data.houseList;
                    $(".floorList").html("");
                    $(".floorList").show();
                    $(".houseList").html("");
                    if(dataList){
                        for (var key in dataList) {
                            var option = '<p class="item"><span class="num">' + key + '</span>层</p>';
                            $(".floorList").append(option);
                            for (var i in dataList[key]) {
                                var content = '<p class="item" dataBuildingArea="' + dataList[key][i].buildingArea + '">' + dataList[key][i].house + '</p>';
                                $(".houseList").append(content);
                            }
                        }
                    }else {
                        $(".projectNameListDiv .alertInfo").text("未找到对应的楼层，请手动输入！").show();
                    }

                }
                else {
                    console.log("获取户接口返回异常：" + data.errorMsg);
                }
            },
            error: function () {
                console.log("获取户接口请求失败");
            }
        });
    }


    // 动态获取小区
    $("#project").bind('input propertychange', function () {
        var inputValue = $(this).val();
        if (!$("#dataProject").text()) {
            $("#projectName").val(inputValue);
            $(".projectNameList").hide();
            getProjectName();
            return;
        }
        if (!$("#dataBuilding").text()) {
            $("#building").val(inputValue);
            $(".buildingList").hide();
            getBuilding();
            return;
        }
        if (!$("#dataUnit").text()) {
            $("#unit").val(inputValue);
            $(".unitList").hide();
            getUnit();
            return;
        }
        if (!$("#dataFloor").text()) {
            $("#floor").val(inputValue);
            $(".floorList").hide()
            getFloorAndHouse();
            return;
        }
        if (!$("#dataHouse").text()) {
            var houseListItem = $(".houseList .item");
            fuzzyQuery(houseListItem, inputValue);
            function fuzzyQuery(houseListItem, inputValue) {
                for (var i = 0; i < houseListItem.length; i++) {

                    if (!(houseListItem.eq(i).text().trim().split(inputValue).length > 1)) {
                        houseListItem.eq(i).hide();
                    }
                    else {
                        houseListItem.eq(i).show();
                    }
                }


            }

        }
    });
    $(".select-list").delegate(" .item", "click", function () {
        $("#project").val("");
    });

    // 动态获取楼栋
    $(".projectNameList").delegate(" .item", "click", function () {
        var housecell = $(this).children("h4").text().trim();
        $("#projectName").val(housecell);
        var communityId = $(this).children("span").text().trim();
        $("#communityId").val(communityId);
        $(".projectNameList").hide();
        $("#dataProject").text(housecell);
        $("#project").val("");
        getBuilding();
    });
    $(".projectNameList").delegate(" h4", "click", function () {
        $(".projectNameList").hide();
    });



    //动态获取单元
    $(".buildingList").delegate(" .item", "click", function () {
        $("#building").val($(this).text().trim());
        $("#buildingId").val($(this).attr("dataBuildingId").trim());
        $(".buildingList").hide();
        $("#dataBuilding").text($(this).text().trim());
        getUnit();
    });


    //动态获取户
    $(".unitList").delegate(" .item", "click", function () {
        $("#unit").val($(this).text().trim());
        $("#unitId").val($(this).attr("dataUnitId").trim());
        $(".unitList").hide();
        $("#dataUnit").text($(this).text().trim());
        getFloorAndHouse();
    });


    $(".floorList").delegate(" .item", "click", function () {
        var floor = $(this).children(".num").text().trim();
        $("#floor").val(floor);
        $(".floorList").hide();
        var totalHouse = $(".houseList .item");
        for (var i = 0; i < totalHouse.length; i++) {
            if (floor != totalHouse.eq(i).text().trim().substring(0, 1)) {
                totalHouse.eq(i).remove();
                $(".houseList").show();
            }

        }
        $("#dataFloor").text($(this).text().trim());
    });


    $(".houseList").delegate(" .item", "click", function () {
        $("#roomNumber").val($(this).text().trim());
        $("#area").val($(this).attr("dataBuildingArea").trim())
        $(".houseList").hide();
        $("#dataHouse").text($(this).text().trim());
    });

    $(".labelgroup").delegate(".item", "click", function () {
        var dataRef = $(this).attr("dataRef");
        $(this).addClass("active").siblings().removeClass("active");
        $(this).children("i.delete").show()
        if (dataRef == "project") {
            $(".select-list").hide();
            $(".projectNameList").show();
        }
        if (dataRef == "building") {
            $(".select-list").hide();
            $(".buildingList").show();
        }
        if (dataRef == "unit") {
            $(".select-list").hide();
            $(".unitList").show();
        }
        if (dataRef == "floor") {
            $(".select-list").hide();
            $(".floorList").show();

        }
        if (dataRef == "house") {
            $(".select-list").hide();
            $(".houseList").show();
            $(".houseList .item").show();
        }
    });


    $(".labelgroup").delegate(".item i.delete", "click", function (event) {
        $("#projectName").val('');
        $("#project").val('');
        var Parent = $(this).parent();
        Parent.removeClass("active");
        event.stopPropagation();
        if (Parent.attr('dataRef') == 'project') {
            $(".labelgroup span[id='dataProject'],.labelgroup span[id='dataBuilding'],.labelgroup span[id='dataUnit'],.labelgroup span[id='dataFloor'],.labelgroup span[id='dataHouse']").text("");
            $("#communityId").val("");
            $("#projectNameList").hide();
            getProjectName();
        }
        if (Parent.attr('dataRef') == 'building') {
            $(".labelgroup span[id='dataBuilding'],.labelgroup span[id='dataUnit'],.labelgroup span[id='dataFloor'],.labelgroup span[id='dataHouse']").text("");
            $("#building").val("");
            $("#buildingList").hide();
            getBuilding();
        }
        if (Parent.attr('dataRef') == 'unit') {
            $(".labelgroup span[id='dataUnit'],.labelgroup span[id='dataFloor'],.labelgroup span[id='dataHouse']").text("");
            $("#unit").val("");
            $("#unitList").hide();
            getUnit();
        }
        if (Parent.attr('dataRef') == 'floor') {

            $(".labelgroup span[id='dataFloor'],.labelgroup span[id='dataHouse']").text("");
            $("#floor").val("");
            $("#floorList").hide();
            getFloorAndHouse();
        }
        if (Parent.attr('dataRef') == 'house') {
            $(".labelgroup span[id='dataHouse']").text("");
            $("#floor").val("");
            $("#houseList").hide();
            getFloorAndHouse();
        }
    })


    $("#building").val("");
    $("#unit").val("");
    $("#area").val("");
    $("#wxcreateStep3Btn").click(function () {

        // 所属城市
        var city = $("#city").val().trim();
        if (!city) {
            helpMessage("请输入所在城市");
            return;
        }

        // 所在区县
        var district = $("#district").val().trim();
        if (!district) {
            helpMessage("请输入所在区县");
            return;
        }

        // 所在小区
        var projectName = $("#projectName").val().trim();
        if (!projectName) {
            helpMessage("请输入所在小区");
            return;
        }

        // 楼栋信息
        var building = $("#building").val().trim();
     /*   if (!building) {
            helpMessage("请输入楼栋信息");
            return;
        }*/

        // 单元信息
        var unit = $("#unit").val().trim();
       /* if (!unit) {
            $("#unit").val(0);
            unit = 0;
        }*/
        // 户号
        var roomNumber = $("#roomNumber").val().trim();
      /*  if (!roomNumber) {
            helpMessage("请输入户号");
            return;
        }*/

        // 面积
        var area = $("#area").val().trim();
        if (!area) {
            helpMessage("请输入住宅面积");
            return;
        }
        if (area <= 0) {
            helpMessage("住宅面积必须大于0");
            return;
        }


        // 询价并提交表单
        $('#wxcreateStep3Btn').addClass("btn_disabled").attr('disabled', 'disabled');
        $.ajax({
            type: "POST",
            url: "/leads/wxQueryPrice",
            data: {
                city: city,
                district: district,
                project: $("#project").val().trim(),
                projectName: projectName,
                building: building,
                unit: unit,
                roomNumber: roomNumber,
                area: area

            },
            beforeSend: function () {
                $(".helpMsg").html("");
                var html = '<h4 class="msg1">评房信息已提交</h4>' + '<h5 class="msg2">系统正在评估中，请稍等 <span class="colorRed">15-30s</span>，返回评房结果</h5>';
                $(html).appendTo($(".helpMsg"));
                $(".helpMsg").fadeIn(200);
            },
            success: function (data) {
                if (data.status == "success") {
                    var price = data.price
                    $("#unitPrice").val(price["unitprice"]);
                    $("#status").val(data["collateralStatus"]);
                    $("#externalId").val(price["evaluateCode"]);
                    $("#wxCreate2Form3").submit();
                    $(".helpMsg").hide();
                } else {
                    helpMessage(data.errorMsg);
                    return;
                }
            }
        });
    });

    setTimeout(function () {
        $(".message").fadeOut(200);
    }, 2000);

    function helpMessage(message) {
        $(".helpMsg").text(message).fadeIn(200);
        setTimeout(function () {
            $(".helpMsg").fadeOut(200);
        }, 2000);
    }

});